const api = require('../../utils/api.js');
const app = getApp();

Page({
  data: {
    backgrop: ['navbar-item-active'],
    navbarArray: [],
    navbarShowIndexArray: 0,
    navigation: false,
    navigation_all: false,
    windowWidth: 375,
    scrollNavbarLeft: 0,
    currentChannelIndex: 0,
    articlesHide: false,
    keyword: '',
    animationData: {},
    showSearch: false,
    theme: app.themeData,
    showAllCat: false,
    showAllCatModel: true,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '暂无专题',
    },
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    imgUrl: app.imgUrl,
    isShowLoading: false,
  },

  onLoad(opts) {
    let id = (opts && opts.type_id) || 0;
    if (opts && opts.shopid) {
      app.ws_micro_shop_globalData.shopid = opts.shopid;
    }
    this.systemInfo = wx.systemInfo;
    app.pageOnLoad(this);
    let _this = this;
    let options = opts || {};
    _this.setData({
      opts: options,
    });
    _this.loadTopicNav(id);
    if (Number(id) === 0) {
      _this.loadTopicList({
        page: 1,
        reload: true,
      });
    }
    wx.getSystemInfo({
      success: res => {
        _this.setData({
          windowWidth: res.windowWidth,
        });
      },
    });
    _this.sortTopic({
      page: 1,
      type: opts.type_id || 0,
      reload: true,
    });
    app
      .loadShopSetting()
      .then(res => {
        _this.setData(res);
      })
      .then(() => {
        _this.getFloatIcon();
      });
  },

  getFloatIcon() {
    let that = this;
    let {
      dial,
      dial_pic,
      contact_tel,
      web_service,
      web_service_url,
      show_customer_service,
      serviceMessageTitle,
      serviceMessagePath,
      service,
      show_qywxcustomer_service,
      show_qywxcustomer_pic,
    } = that.data;
    that.setData({
      floatItems: [
        {
          type: 1, // 客服电话
          show: dial == 1,
          icon: dial_pic,
          tel: contact_tel,
        },
        {
          type: 6, // 企业客服
          show: Number(show_qywxcustomer_service) === 1,
          icon: show_qywxcustomer_pic,
        },
        {
          type: 3, // webview跳转
          show: web_service,
          icon: web_service,
          url: web_service_url,
        },
        {
          type: 4, // 客服跳转
          show: show_customer_service && show_customer_service == 1,
          icon: service,
          sessionFormStr: JSON.stringify({
            shop_id: app.ws_micro_shop_globalData.shopid,
          }),
          serviceMessageTitle: serviceMessageTitle,
          serviceMessagePath: serviceMessagePath,
        },
      ],
    });
  },

  onShow() {
    let animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    });
    this.animation = animation;
  },

  toggleShowSearch() {
    let _switch = this.data.showSearch;
    if (_switch) {
      this.animation.width(0 + 'rpx').step();
      this.setData({
        animationData: this.animation.export(),
        showSearch: false,
        keyword: '',
      });
    } else {
      this.animation.width(630 + 'rpx').step();
      this.setData({
        animationData: this.animation.export(),
        showSearch: true,
      });
    }
  },

  getSearchTxt(e) {
    let text = e.detail.value;
    this.setData({
      keyword: text,
    });
  },

  sureSearch() {
    let keywords = this.data.keyword.trim();
    let typeIndex = this.data.currentChannelIndex;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    this.sortTopic({
      page: 1,
      keywords,
      type: typeIndex,
      reload: true,
    });
  },

  loadTopicNav(id) {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.default.topic_type,
      data: {},
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            navbarArray: res.data.list || [],
            navbarShowIndexArray: Array.from(
              Array(res.data.list.length).keys()
            ),
            navigation_all: res.data.list.length === 0 ? false : true,
            navigation: (res.data.list.length === 0 || res.data.chosen === 0) ? false : true,
          });
          _this.switchChannel(id, res.data.list);
          let query = wx.createSelectorQuery();
          query.select('.navbar-item-active').boundingClientRect();
          query.selectViewport().scrollOffset();
          query.exec(function(res) {
            let l = res[0] ? res[0].left : 0;
            _this.setData({
              scrollNavbarLeft: l - 150,
            });
          });
          let scroll_width = 0;
          let scrollview = wx.createSelectorQuery();
          scrollview.select('.nnavbar').boundingClientRect();
          scrollview.selectViewport().scrollOffset();
          scrollview.exec(function(res) {
            scroll_width = res[0] ? res[0].width : 0;
          });
          let children = wx.createSelectorQuery();
          children.selectAll('.navbar-item').boundingClientRect();
          children.selectViewport().scrollOffset();
          children.exec(function(res) {
            let child = res[0];
            let width = child[child.length - 1]
              ? child[child.length - 1].right
              : 0;
            _this.setData({
              showAllCat: width > scroll_width,
            });
          });
        }
      },
    });
  },

  loadTopicList(args) {
    let _this = this;
    if (_this.data.is_loading) {
      return;
    }
    if (args.loadmore && !_this.data.is_more) {
      return;
    }
    _this.setData({
      is_loading: true,
    });
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.topic_list,
      data: {
        page: args.page,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          // 判断是否是加载第一页
          if (args.reload) {
            _this.setData({
              list: res.data.list || [],
              page: args.page,
              is_more: res.data.list.length > 0,
            });
          }
          // 判断是否是加载分页
          if (args.loadmore) {
            _this.setData({
              list: _this.data.list.concat(res.data.list),
              page: args.page,
              is_more: res.data.list.length > 0,
            });
          }
        }
      },
      complete: function() {
        _this.setData({
          is_loading: false,
          isShowLoading: true,
        });
      },
    });
  },

  onPullDownRefresh() {
    let currentChannelIndex = this.data.currentChannelIndex;
    this.switchChannel(
      parseInt(currentChannelIndex, 10),
      this.data.navbarArray
    );
    this.sortTopic({
      page: 1,
      type: parseInt(currentChannelIndex, 10),
      reload: true,
    });
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    let currentChannelIndex = this.data.currentChannelIndex;
    let _this = this;
    this.switchChannel(
      parseInt(currentChannelIndex, 10),
      this.data.navbarArray
    );
    this.sortTopic({
      page: _this.data.page + 1,
      keywords: _this.data.keyword,
      type: parseInt(currentChannelIndex, 10),
      loadmore: true,
    });
  },

  onTapNavbar(e) {
    let offsetLeft = e.currentTarget.offsetLeft;
    let scrollLeft = this.data.scrollNavbarLeft;
    scrollLeft = offsetLeft - 110;
    this.setData({
      scrollNavbarLeft: scrollLeft,
      // showAllCatModel: false,
      isShowLoading: false,
    });
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    this.switchChannel(parseInt(e.currentTarget.id, 10), this.data.navbarArray);
    this.sortTopic({
      page: 1,
      keywords:this.data.keyword,
      type: e.currentTarget.id,
      reload: true,
    });
  },

  sortTopic(args) {
    let _this = this;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.topic_list,
      data: args,
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          if (args.reload) {
            _this.setData({
              list: res.data.list || [],
              page: args.page,
              is_more: res.data.list.length > 0,
            });
          }
          if (args.loadmore && Boolean(args.loadmore)) {
            _this.setData({
              list: _this.data.list.concat(res.data.list),
              page: args.page,
              is_more: res.data.list.length > 0,
            });
          }
          wx.hideLoading();
        }
      },
      complete: function () {
        _this.setData({
          isShowLoading: true,
        })
      }
    });
  },

  switchChannel(index, navlist) {
    let targetChannelIndex = Number(index);
    let navbarArray = navlist;
    let backgrop = [];
    if (targetChannelIndex === -1) {
      backgrop[1] = 'navbar-item-active';
    } else if (targetChannelIndex === 0) {
      backgrop[0] = 'navbar-item-active';
    }

    navbarArray.forEach(item => {
      item.type = '';
      if (Number(item['id']) === targetChannelIndex) {
        item.type = 'navbar-item-active';
      }
    });
    this.setData({
      navbarArray: navbarArray,
      currentChannelIndex: targetChannelIndex,
      backgrop: backgrop,
    });
  },

  onShareAppMessage() {
    return {
      path:
        '/ws_micro_shop/pages/topic-list/topic-list?shopid=' +
        app.ws_micro_shop_globalData.shopid,
    };
  },
  onShareTimeline() {
    return {
      title: '',
      imageUrl: '',
      query: 'shopid=' +
      app.ws_micro_shop_globalData.shopid
    }
  },
  collectFormId(e) {
    app.collectFormId(e);
  },

  catchTap() {
    // it`s necessary
  },

  toggleAllCatModel() {
    this.setData({
      showAllCatModel: !this.data.showAllCatModel,
    });
  },

  showAllCatModel() {
    this.setData({
      showAllCatModel: true,
    });
  },

  hideAllCatModel() {
    this.setData({
      showAllCatModel: false,
    });
  },
});
